package com.demo.config.mq;

import javax.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;

/**
 * Rabbitmq 配置
 *
 */
@Slf4j
@Configuration
public class MyRabbitmqConfig {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Qualifier("myMessageConverter")
    @Autowired
    private MessageConverter messageConverter;

    @PostConstruct
    public void initRabbitTemplate() {
        // 只要消息抵达服务器，就会触发该回调
        rabbitTemplate.setConfirmCallback((correlationData, ack, failCause) ->
                log.info("send success -> correlationData=[{}],ack=[{}],failCause=[{}]", correlationData, ack, failCause)
        );
        // 设置消息抵达队列的确认回调，如果消息没有成功投递到指定队列，就会触发该回调
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) ->
                log.info("send fail -> message=[{}],replyCode=[{}],replyText=[{}],exchange=[{}],routingKey=[{}]",
                        message, replyCode, replyText, exchange, routingKey)
        );
        // jackson
        rabbitTemplate.setMessageConverter(messageConverter);
        log.info("rabbitmq start success");
    }
}
